import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

SEPARATOR = ","
QUOTE     = "\""
NEWLINE = System.getProperty("line.separator")
SEPARATOR = File.separator
SPACING = "    "

buffer = new StringBuilder()

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        fields += [[
                           name : col.getName(),
                           type : spec,
                           annos: col.getComment()]]
    }
}

def generate(buffer, table) {
    def className = table.getName()
    def tableComment = table.getComment()

    buffer.append(NEWLINE)
    buffer.append("## Table:  `$className` `$tableComment`")
    buffer.append(NEWLINE).append(NEWLINE)
    println className

    buffer.append("|          COLUMN         |         TYPE           |         COMMENT           |").append(NEWLINE)
    buffer.append("|-------------------------|------------------------|------------------------|").append(NEWLINE)
    def fields = calcFields(table)
    fields.each() {
        buffer.append("| ${it.name} | ${it.type} | ${it.annos} | ").append(NEWLINE)
    }
    buffer.append(NEWLINE)
}

SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(buffer,it) }

CLIPBOARD.set(buffer.toString())